package se.topshelf.golftracker.core.domain;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;

import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.regex.Pattern;

/**
 *
 */
@Embeddable
public class GolfId implements Serializable, Comparable<GolfId>{
    @NotNull

    private String golfId;
    private static final String birthDateRegularExpression = "[0-9]{2}[0-1][0-9][0-3][0-9]";
    private static final String orderRegularExpression = "[0-9]{3}";


    // For O/R-mapper only
    GolfId() {
    }

    private GolfId(String golfId) {
        this.golfId = golfId;

    }

    /**
     * Factory that creates GolfIds
     *
     * @param birthDate, numbers of form yyMMdd
     * @param order, numbers of form nnn
     * @return newly created GolfId instance
     * @throws IllegalArgumentException if any input is illegal
     */
    public static GolfId createGolfId(String birthDate, String order) {
        if(!Pattern.matches(birthDateRegularExpression, birthDate)){
            throw new IllegalArgumentException("Illegal birthdate, must be of form 'yyMMdd was: " + birthDate);
        }
        if(!Pattern.matches(orderRegularExpression, order)){
            throw new IllegalArgumentException("Illegal order, must be of form 'nnn' was:" + order);
        }
        return new GolfId(birthDate + "-" + order);
    }


    public  String getAsString(){
        return golfId;
    }

    public int compareTo(GolfId other) {
       return new CompareToBuilder().append(golfId, other.golfId).toComparison();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        GolfId other = (GolfId) o;

        return new EqualsBuilder().append(golfId, other.golfId).isEquals();
    }

    @Override
    public int hashCode() {
        return golfId.hashCode();
    }
}
